package com.bwie.boot.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.transaction.Transactional;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.bwie.boot.dao.UserDao;
import com.bwie.boot.entity.User;

import util.IdWorker;

@Service
public class UserService {

	 @Autowired
	 private RedisTemplate  redisTemplate;
	
	 @Autowired
	 private RabbitTemplate  rabbitTemplate;
	  
	 @Autowired
	 BCryptPasswordEncoder encoder;
	 
	 @Autowired
	 private UserDao dao;
	 
	 @Autowired
	 private IdWorker idWorker;
	 
	 public  void sendSms(String mobile) {
		 Random random = new Random();
		 
		 int max=999999;
		 int min=100000;
		 int code=random.nextInt(max);
		 if(code<min) {
			 code=code+min;
		 }
		 System.out.println(mobile+"收到验证码"+code);
		redisTemplate.opsForValue().set("smscode_"+mobile,code+"", 5,TimeUnit.MINUTES);;
	    HashMap<String, Object> map = new HashMap<String,Object>();
	    map.put("mobile", mobile);
	    map.put("code", code+"");
	     rabbitTemplate.convertAndSend("sms",map);
	 
	 }


	public void add(User user, String code) {
		// TODO Auto-generated method stub
		//获取redis的短信
		String syscode = (String) redisTemplate.opsForValue().get("smscode_"+user.getMobile());
		System.out.println(syscode);
	   //判断验证码是否过期
		if(syscode==null) {
			 throw new RuntimeException("请点击获取验证码");
		}
		if(!syscode.equals(code)) {
			 throw new RuntimeException("输入的验证码不正确");
		}
		  String encode = encoder.encode(user.getPassword());
		user.setPassword(encode);
		user.setId( idWorker.nextId()+"" );
		user.setFollowcount(0);//关注数
		user.setFanscount(0);//粉丝数
		user.setOnline(0L);//在线时长
		user.setRegdate(new Date());//注册日期
		user.setUpdatedate(new Date());//更新日期
		user.setLastdate(new Date());//最后登陆日期
		dao.save(user);
	}

   /* public void save(User user) {
    	
    }*/
	
	
	public User findByLoginnameAndPassword(String loginname, String password) {
		// TODO Auto-generated method stub
	   User u= dao.findByLoginname(loginname);
		 if(u!=null && encoder.matches(password, u.getPassword())) {
			  return u;
		 }else {
			 return  null;
		 }
		
		
	}


	public void delete(String id) {
		// TODO Auto-generated method stub
		 dao.deleteById(id);
	}

    @Transactional
	public void incFanscount(String userid, int x) {
		// TODO Auto-generated method stub
		 dao.incFanscount(userid,x);
	}

   @Transactional
	public void incfollow(String userid, int x) {
		// TODO Auto-generated method stub
		 dao.incfollow(userid,x);
	}
	
}
